import { User } from '../types';
import apiClient from './client';

// 获取验证码
export const getCaptcha = async () => {
  const response = await apiClient.get('/u/v1/code/captcha');
  return {
    captchaId: response.data.captchaId,
    picPath: response.data.picPath
  };
};

// 发送短信验证码
export const sendSmsCode = async (mobile: string, type: number = 1) => {
  const response = await apiClient.post('/u/v1/code/send_sms', {
    mobile,
    type
  });
  return response.data;
};

// 用户注册
export const register = async (userData: {
  mobile: string;
  password: string;
  code: string;
}) => {
  const response = await apiClient.post('/u/v1/user/register', userData);
  const data = response.data;

  // 确保返回的数据结构一致
  if (data.user && !data.user.nick_name) {
    data.user.nick_name = data.user.nickname || data.user.userName || data.user.username || '用户';
  }

  return data;
};

// 用户登录
export const login = async (credentials: {
  mobile: string;
  password: string;
  captcha: string;
  captcha_id: string;
}) => {
  const response = await apiClient.post('/u/v1/user/login', credentials);
  const data = response.data || {};

  // 记录原始响应数据（不包含敏感信息）
  console.log('Login API raw response:', {
    responseType: typeof data,
    hasData: !!data,
    dataKeys: Object.keys(data),
    timestamp: new Date().toISOString()
  });

  // 获取token（可能在根级别或data子对象中）
  let token = data.token || data.access_token || data.accessToken;
  if (!token && data.data) {
    token = data.data.token || data.data.access_token || data.data.accessToken;
  }

  // 检查是否有必要的用户信息字段
  const hasRequiredFields = data.id !== undefined &&
                          data.role !== undefined &&
                          (data.nick_name !== undefined || data.nickname !== undefined);

  // 处理不同的响应格式
  let userInfo;

  // 情况1: 用户信息在根级别（扁平结构）
  if (hasRequiredFields) {
    userInfo = {
      id: data.id,
      nick_name: data.nick_name || data.nickname || data.userName || data.username || String(data.mobile) || '用户',
      role: data.role,
      expired_at: data.expired_at
    };
  }
  // 情况2: 用户信息在user对象中
  else if (data.user && typeof data.user === 'object') {
    const user = data.user;
    userInfo = {
      id: user.id || user.userId || user.user_id || 0,
      nick_name: user.nick_name || user.nickname || user.userName || user.username || String(user.mobile) || '用户',
      role: user.role,
      expired_at: user.expired_at
    };
  }
  // 情况3: 用户信息在data子对象中
  else if (data.data && typeof data.data === 'object') {
    const nestedData = data.data;
    userInfo = {
      id: nestedData.id || nestedData.userId || nestedData.user_id || 0,
      nick_name: nestedData.nick_name || nestedData.nickname || nestedData.userName || nestedData.username || String(nestedData.mobile) || '用户',
      role: nestedData.role,
      expired_at: nestedData.expired_at
    };
  }

  // 验证必要数据是否存在
  if (!token || !userInfo) {
    console.error('Login response validation failed:', {
      hasToken: !!token,
      hasUserInfo: !!userInfo,
      originalData: data
    });
    throw new Error('登录响应数据不完整或格式错误');
  }

  // 确保过期时间格式正确（转换为秒级时间戳）
  if (userInfo.expired_at > 9999999999) { // 如果是毫秒时间戳
    userInfo.expired_at = Math.floor(userInfo.expired_at / 1000);
  } else if (!userInfo.expired_at) {
    userInfo.expired_at = Math.floor(Date.now() / 1000) + 86400; // 默认24小时
  }

  // 打印处理后的用户数据（不包含敏感信息）
  console.log('Processed login response:', {
    hasToken: true,
    user: {
      id: userInfo.id,
      nick_name: userInfo.nick_name,
      role: userInfo.role,
      expired_at: userInfo.expired_at,
      expiry_time: new Date(userInfo.expired_at * 1000).toLocaleString()
    },
    timestamp: new Date().toISOString()
  });

  return { token, user: userInfo };
};

// 获取当前用户信息
export const getCurrentUser = async (): Promise<User> => {
  const response = await apiClient.get('/auth/me');
  return response.data;
};

// 退出登录
export const logout = () => {
  localStorage.removeItem('token');
  // 不直接跳转，而是通过 Redux 状态管理来处理重定向
  return { success: true };
};